package api

import (
	"minio-webhook/model"
	"minio-webhook/service"
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

func HandleWebhook(c *gin.Context) {
	var event model.WebhookEvent

	if err := c.ShouldBindJSON(&event); err != nil {
		logrus.WithFields(logrus.Fields{
			"error": err.Error(),
		}).Error("Failed to bind JSON")
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	logrus.WithFields(logrus.Fields{
		"Add upload": event.Key,
	}).Info("Received Key")

	err := service.PreHostUrls([]string{os.Getenv("CDN_URL") + "/" + event.Key})
	if err != nil {
		logrus.WithFields(logrus.Fields{
			"error": err.Error(),
		}).Error("Failed to prehost URLs")
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to prehost URLs"})
		return
	}

	c.String(http.StatusOK, event.Key)
}
